import { ref, onUnmounted, onMounted } from 'vue'

export function useDevice() {
  const isMobileRef = ref(false)

  onMounted(() => {
    resetWin()
    window.onresize = resetWin
  })

  onUnmounted(() => {
    window.onresize = null
  })

  function checkIsMobile(cb) {
    var offsetWid = document.documentElement.clientWidth
    var isMobile = offsetWid <= 768
    cb && cb(isMobile, offsetWid)
  }

  function resetWin() {
    checkIsMobile((_isMobile) => {
      if (_isMobile !== isMobileRef.value) {
        isMobileRef.value = _isMobile
      }
    })
  }

  return {
    resetWin,
    checkIsMobile,
    isMobileRef
  }
}
